from django.shortcuts import render,HttpResponse
import requests
from app1.models import UserInfo
import app1.models as models
import json
import app1.identify as car
from time import sleep
# Create your views here.
def index(request):
    # # 增
    UserInfo.objects.create(name="lan", passward="123456", question="你是谁？")
    # # 删除
    # UserInfo.objects.filter(id=1).delete()
    # print(request.GET['name'])
    # find
    row_obj= UserInfo.objects.filter(name="兰").first()
    # print(row_obj.id,row_object.name)
    # modify
    # row_obj= UserInfo.objects.filter(name="兰").update(passward="123")
    # print(row_obj.id,row_object.name)
    js={"reason":"success","result":{"text":"507爱是美丽的忧伤，爱是甜美的心碎。看着一个熟悉的背影，最后消失在自己的视线里，双唇颤抖着，心却已无言。"},"error_code":0}

    res =  requests.get('https://apis.juhe.cn/fapig/soup/query?key=125d1d2ea49e35337667d7c7f70f15e1')
    # UserInfo.objects.create(name="兰",passward="123456",question="你是谁？")
    return HttpResponse(str(js))


def login(request):
    name=request.GET['name']
    passward=request.GET['passward']
    row_obj=UserInfo.objects.filter(name=name,passward=passward)
    result={}
    res={"reason":"success","result":{'name':'123'},"error_code":""}
    if(len(row_obj) == 0):
        res['error_code']="-1"
        return HttpResponse(json.dumps(res))
    else:
        result['name']=name
        res['result']=result
        return HttpResponse(json.dumps(res))

def register(request):
    name = request.GET['name']
    passward = request.GET['passward']
    question=request.GET['question']
    answer=request.GET['answer']
    row_obj=UserInfo.objects.filter(name=name)
    res = {"reason": "success", "result": {'name':'123'}, "error_code": ""}
    if(len(row_obj)==0):
        UserInfo.objects.create(name=name,passward=passward,question=question,answer=answer)
        return HttpResponse(json.dumps(res))
    else:
        res['error_code']="-1"
        return HttpResponse(json.dumps(res))
def find_username(request):
    name = request.GET['name']
    row_obj = UserInfo.objects.filter(name=name)
    res = {"reason": "success", "result": {'name':'-1'}, "error_code": "-1"}
    if(len(row_obj)==0):
        return HttpResponse(json.dumps(res))
    else:
        res['error_code']="1"
        result={'name':'0'}
        result['name']=row_obj[0].question
        res['result']=result
        return HttpResponse(json.dumps(res))
def find_answer(request):
    name = request.GET['name']
    answer=request.GET['answer']
    row_obj = UserInfo.objects.filter(name=name,answer=answer)
    res = {"reason": "success", "result": {'name':'1'}, "error_code": "-1"}
    if(len(row_obj)==0):
        return HttpResponse(json.dumps(res))
    else:
        res['error_code']="1"
        result={'name':'0'}
        result['name']=row_obj[0].passward
        res['result']=result
        return HttpResponse(json.dumps(res))



def car_list(request):
    res = {"reason": "success", "result": {'name': '-1'}, "error_code": "1"}
    name = request.GET['name']
    row_obj = models.CarInfo.objects.filter(name=name)
    car_user_name=[]
    car_time=[]
    car_exist=[]
    for i in row_obj:
        car_user_name.append(i.car_user_name)
        car_time.append(i.car_time)
        car_exist.append(i.car_exist)
    result={'car_user_name':[],'car_time':[],'car_exist':[]}
    result['car_user_name']=car_user_name
    result['car_time'] = car_time
    result['car_exist'] = car_exist
    res['result']=result
    return HttpResponse(json.dumps(res))

def delete_car(request):
    name = request.GET['name']
    car_user_name=request.GET['car_user_name']
    models.CarInfo.objects.filter(name=name,car_user_name=car_user_name).delete()
    res = {"reason": "success", "result": {'name': '-1'}, "error_code": "1"}
    return HttpResponse(json.dumps(res))

def test(request):

    print("ok")
    if request.method == 'POST':
        res = {"reason": "success", "result": {'name': '1'}, "error_code": "-1"}
        file_ob=request.FILES.get('file')
        print(file_ob)
        f = open("image/"+file_ob.name,mode="wb")
        for chunk in file_ob.chunks():
            f.write(chunk)
        print(type(file_ob))
        concat = request.POST
        print(concat)
        print(file_ob)
        # img = request.POST['data']
        # print(request.POST['data'])
        # print(img)
        # with open(img.name, 'wb') as f:
        #     for line in img:
        #         f.write(line)
        # print('打印名称和类型', type(img), img)
        HttpResponse(json.dumps(res))
    print(request)

    return HttpResponse("ok!")


def identify_car(request):
    res = {"reason": "1", "result": {'name': '1'}, "error_code": "0"}
    if request.method == 'POST':
        print("收到post")
        name = request.GET['name']
        identy=request.GET['identy']
        file_ob = request.FILES.get('file')
        f = open("image/" + file_ob.name, mode="wb")
        for chunk in file_ob.chunks():
            f.write(chunk)
        result = car.get_license_plate('image/' + file_ob.name)
        if (result == "None"):
            res['error_code'] = '1'
            models.CarInfo.objects.create(name=name, car_card="a", car_exist="",
                                          car_user_name="car_user_name", car_time="car_time", phone_number="phone_number",identy=identy)
            print("未识别到车辆")
        else:
            car_card = result['Number']
            row_obj = models.CarInfo.objects.filter(name=name, car_card=car_card)
            if len(row_obj) == 0:
                print("2")
                print("数据库没有这辆车")
                models.CarInfo.objects.create(name=name, car_card="b", car_exist="",
                                              car_user_name="", car_time="",
                                              phone_number="",identy=identy)
            else:
                models.CarInfo.objects.filter(name=name, car_card=car_card).update(identy=identy)
                print("识别成功")
        return HttpResponse("ok")

    if request.method == 'GET':
        sleep(5)
        print("收到get")
        name = request.GET['name']
        identy = request.GET['identy']
        row_obj = models.CarInfo.objects.filter(name=name, identy=identy)
        if len(row_obj) == 0:
            res['error_code'] = "-1"
            return HttpResponse(json.dumps(res))
        else :
            if row_obj[0].car_card =="a":
                res['error_code'] = "1"
                models.CarInfo.objects.filter(name=name, identy=identy).delete()
                return HttpResponse(json.dumps(res))
            elif row_obj[0].car_card =="b":
                res['error_code']='1'
                models.CarInfo.objects.filter(name=name, identy=identy).delete()
                return HttpResponse(json.dumps(res))
            else:
                reason=row_obj[0].car_exist
                res['reason']=reason
                if reason=="1":
                    models.CarInfo.objects.filter(name=name,identy=identy).update(car_exist="0")
                else:
                    models.CarInfo.objects.filter(name=name, identy=identy).update(car_exist="1")
                return HttpResponse(json.dumps(res))



def car_register(request):
    res = {"reason": "success", "result": {'name': '1'}, "error_code": "0"}
    if request.method == 'POST':
        print("ok")
        name=request.GET['name']
        print(name)
        car_user_name=request.GET['car_user_name']
        car_time = request.GET['car_time']
        car_exist=request.GET['car_exist']
        phone_number=request.GET['phone_number']
        file_ob = request.FILES.get('file')
        f = open("image/" + file_ob.name, mode="wb")
        for chunk in file_ob.chunks():
            f.write(chunk)
        result = car.get_license_plate('image/' + file_ob.name)
        if(result=="None"):
            res['error_code']='1'
            models.CarInfo.objects.create(name=name, car_card="s", car_exist=car_exist,
                                          car_user_name=car_user_name, car_time=car_time, phone_number=phone_number)
            print("1")
        else:
            car_card=result['Number']
            row_obj=models.CarInfo.objects.filter(name=name,car_card=car_card)

            if len(row_obj)==0:
                print("2")
                models.CarInfo.objects.create(name=name,car_card=car_card,car_exist=car_exist,car_user_name=car_user_name,car_time=car_time,phone_number=phone_number,node="100")
                print(car_card)
            else:
                models.CarInfo.objects.create(name=name, car_card=car_card, car_exist=car_exist,
                                              car_user_name=car_user_name, car_time=car_time, phone_number=phone_number,
                                              node="1")
            return HttpResponse("ok")

    if request.method == 'GET':
        sleep(5)
        name = request.GET['name']
        car_user_name = request.GET['car_user_name']
        car_time = request.GET['car_time']
        car_exist = request.GET['car_exist']
        phone_number = request.GET['phone_number']
        row_obj=models.CarInfo.objects.filter(name=name,car_exist=car_exist,car_user_name=car_user_name,car_time=car_time,phone_number=phone_number)
        if len(row_obj) ==0:
            res['error_code']="3"
            return HttpResponse(json.dumps(res))
        if row_obj[0].car_card =="s":
            res['error_code']="1"
            models.CarInfo.objects.filter(name=name, car_card="s",car_exist=car_exist, car_user_name=car_user_name,
                                                    car_time=car_time, phone_number=phone_number).delete()
            return HttpResponse(json.dumps(res))
        elif row_obj[0].node=="1":
            res['error_code'] = "2"
            models.CarInfo.objects.filter(name=name, car_exist=car_exist,
                                              car_user_name=car_user_name, car_time=car_time, phone_number=phone_number,
                                              node="1").delete()
            return HttpResponse(json.dumps(res))
        else:
            res['error_code'] = "0"
            return HttpResponse(json.dumps(res))



#     http://192.168.31.231:8000/car_register/?name=lan&car_user_name=123456&car_time=1&car_exist=2&phone_number=2
